package com.fita.wechat.handler.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.fita.wechat.Constant;
import com.fita.wechat.handler.SmsHandler;
import com.fita.wechat.rao.SmsRao;

/**
 * 
 * @author mohanlan
 *
 */
@Component("smsHandler")
public class SmsHandlerImpl implements SmsHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsHandlerImpl.class);
    
    @Value("#{ctx['sms.host']}")
    private String host;
    
    @Value("#{ctx['sms.mock']}")
    private boolean mock;
    
    @Value("#{ctx['ctx.domain']}")
    private String systemHost;
    
    @Rao
    private SmsRao smsRao;
    
    /* (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#generateVerifyCode(java.lang.String)
     */
    public String generateVerifyCode(String mobile) {
        return RandomStringUtils.randomNumeric(6);
    }

    /* (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#sendVerifyCode(java.lang.String, java.lang.String)
     */
    public boolean sendVerifyCode(String mobile, String code) {
        
        HttpResult httpResult = new HttpResult();
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", "【"+ Constant.SMS_COMPANY_NAME +"】您的验证码是" + code);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        
        String url = host + "/send-sms";
        
        logger.info("url is [{}]", url);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));
        
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));
        
        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(url, parameters);
        
        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));
        return httpResult.isValid();
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#sendOrderMessage(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean sendOrderMessage(String mobile, String surname, String name, String code, String pdfUrl, String url) {
        HttpResult httpResult = new HttpResult();
        
        String fullName = surname + "/" + name;
        String message = "【"+ Constant.SMS_ORDER_COMPANY_NAME +"】" + fullName + "的租车订单" + code + "已确认！取车确认书：" + systemHost + "/" + pdfUrl + "。详情请戳" + systemHost + "/" + url;
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", message);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        
        String sendUrl = host + "/send-sms";
        
        logger.info("url is [{}]", sendUrl);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));
        
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));
        
        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(sendUrl, parameters);
        
        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));
        return httpResult.isValid();
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#sendOrderStayingMessage(java.lang.String, java.lang.String, java.lang.String, java.util.Date, java.util.Date, java.lang.String)
     */
    public boolean sendOrderStayingMessage(String mobile, String supplierName, String code, Date startDate, Date endDate, String url) {
        HttpResult httpResult = new HttpResult();
        
        String currentStartDate = DateFormatUtils.format(startDate, "yyyy年MM月dd日");
        String currentEndDate = DateFormatUtils.format(endDate, "yyyy年MM月dd日");
        long num = (endDate.getTime() - startDate.getTime())/(24*60*60*1000);
        String payEndDate = DateFormatUtils.format(DateUtils.addDays(startDate, -5), "yyyy年MM月dd日 HH:mm:ss");
        String message = "【"+ Constant.SMS_ORDER_COMPANY_NAME +"】您的" + supplierName + "租车订单" + code + "已保留！用车时间：" + currentStartDate + "至" + currentEndDate + "，共" + num + "天。订单将保留至" + payEndDate + "前，请及时支付以免租车价格发生变化。点击支付，请戳" + systemHost + "/" + url;
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", message);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        
        String sendUrl = host + "/send-sms";
        
        logger.info("url is [{}]", sendUrl);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));
        
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));
        
        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(sendUrl, parameters);
        
        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));
        return httpResult.isValid();
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#sendOrderCancelMessage(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean sendOrderCancelMessage(String mobile, String code, String url) {
        HttpResult httpResult = new HttpResult();
        
        String message = "【"+ Constant.SMS_ORDER_COMPANY_NAME +"】尊敬的会员，您预定的" + code + "已取消，重新预定请戳" + systemHost + "/" + url;
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", message);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        
        String sendUrl = host + "/send-sms";
        
        logger.info("url is [{}]", sendUrl);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));
        
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));
        
        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(sendUrl, parameters);
        
        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));
        return httpResult.isValid();
    }

    /*
     * (non-Javadoc)
     * @see com.fita.wechat.processor.SmsSender#checkVerifyCode(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean checkVerifyCode(String mobile, String code, String token) {
        String vtoken = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, Constant.SMS_CLIENT));
        return org.apache.commons.lang3.StringUtils.equals(vtoken, token);
    }

    /* (non-Javadoc)
     * @see com.fita.wechat.handler.SmsHandler#sendMessage(java.lang.String, java.lang.String)
     */
    public boolean sendMessage(String mobile, String content) {
        
        HttpResult httpResult = new HttpResult();
        
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", content);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));
        
        String url = host + "/send-sms";
        
        logger.info("url is [{}]", url);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));
        
        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(url, parameters);
        
        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));
        
        return httpResult.isValid();
        
    }


    /**
     *
     * @param mobile
     * @param content
     * @return
     */
    public boolean sendAuditSuccessMessage(String mobile, String content) {

        HttpResult httpResult = new HttpResult();
        HashMap<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("message", content);
        parameters.put("mobiles", mobile);
        parameters.put("time", "0");
        logger.info("start call sms with message [{}], mobiles [{}]", parameters.get("message"), parameters.get("mobiles"));

        String url = host +"/send-sms";
        logger.info("url is [{}]", url);
        logger.info("pramas is [{}]", JsonUtils.toJson(parameters));

        httpResult = mock ? httpResult.success().message("发送成功") : smsRao.smsSender(url, parameters);

        logger.info("sendMessage get result [{}]", JsonUtils.toJson(httpResult));

        return httpResult.isValid();
    }

}
